import json

from rest_framework import serializers
from apps.base_app.utils import get_md5
from apps.base_app.models import (
    SeniorList,
    StudentsList,
    WorkList,
    WorkManage,
    Direction,
)
from config.constant import (
    QQ_ID_MAX_LENGTH,
    GROUP_NAME,
    DIRECTION_NAME,
    MAX_MARKDOWN_SIZE,
)


class SeniorListSerializer(serializers.Serializer):
    name = serializers.CharField(max_length=7)
    stu_id = serializers.CharField(max_length=10, min_length=10)
    password = serializers.CharField(max_length=16, min_length=8, write_only=True)
    qq_id = serializers.CharField(max_length=QQ_ID_MAX_LENGTH)  # 目前最长10位，未来可能会更长
    group = serializers.CharField()  # 给前端和前端给的都是字符串，存本地才是数字
    direction = serializers.CharField()
    is_active = serializers.BooleanField(default=False)  # 学长学姐是否通过了他的注册
    is_root = serializers.BooleanField(default=False)  # 默认不是root

    email = serializers.EmailField(allow_blank=True, allow_null=True)
    phone = serializers.CharField(allow_blank=True, allow_null=True, max_length=11, min_length=11)

    class Meta:
        model = SeniorList
        fields = ('name', 'stu_id', 'password', 'qq_id', 'group', 'direction', 'is_active', 'is_root', 'email', 'phone')

    def to_internal_value(self, data):  # 前端的json传到后端转化为数据库格式
        # data = json.loads(data)
        return data

    def to_representation(self, instance):  # 修改默认映射，这里得改，因为dg_id!!!!!!!! todo todo todo !!!
        instance.group = Direction.get_group(instance.dg_id)
        instance.direction = Direction.get_direction(instance.dg_id)
        return super(SeniorListSerializer, self).to_representation(instance)

    def create(self, validated_data):
        validated_data['password'] = get_md5(validated_data['password'])
        if validated_data.get('group', None) and validated_data.get('direction'):
            validated_data['dg_id'] = Direction.get_pk(validated_data.get('group', None), validated_data.get('direction'))
            validated_data.pop('group')
            validated_data.pop('direction')
        instance = self.Meta.model.objects.create(**validated_data)
        return instance

    def update(self, instance, validated_data):
        for attr in self.Meta.fields:
            if attr != 'group' and attr != 'direction':
                setattr(instance, attr, validated_data.get(attr, getattr(instance, attr)))
        if hasattr(validated_data, 'group') and hasattr(validated_data, 'direction'):
            setattr(instance, 'dg_id',
                    Direction.get_pk(getattr(validated_data, 'group'), getattr(validated_data, 'direction')))
        instance.save()
        return instance


class StudentsListSerializer(serializers.Serializer):
    name = serializers.CharField(max_length=7)
    stu_id = serializers.CharField(max_length=10, min_length=10)
    password = serializers.CharField(max_length=16, min_length=8, write_only=True)
    qq_id = serializers.CharField(max_length=QQ_ID_MAX_LENGTH)  # 目前最长10位，未来可能会更长
    group = serializers.CharField()
    direction = serializers.CharField()
    is_active = serializers.BooleanField(default=False)  # 学长学姐是否通过了他的注册
    accompany = serializers.BooleanField(default=True)  # 是否还和云顶在一起

    email = serializers.EmailField(allow_blank=True, allow_null=True)
    phone = serializers.CharField(allow_blank=True, allow_null=True, max_length=11, min_length=11)

    class Meta:
        model = StudentsList
        fields = (
        'name', 'stu_id', 'password', 'qq_id', 'group', 'direction', 'is_active', 'accompany', 'email', 'phone'
        )

    def to_internal_value(self, data):  # 前端的json传到后端转化为数据库格式
        return data

    def to_representation(self, instance):  # 修改默认映射
        instance.group = Direction.get_group(instance.dg_id)
        instance.direction = Direction.get_direction(instance.dg_id)
        return super(StudentsListSerializer, self).to_representation(instance)

    def create(self, validated_data):
        validated_data['password'] = get_md5(validated_data['password'])
        if validated_data.get('group', None) and validated_data.get('direction'):
            validated_data['dg_id'] = Direction.get_pk(validated_data.get('group', None), validated_data.get('direction'))
            validated_data.pop('group')
            validated_data.pop('direction')
        instance = self.Meta.model.objects.create(**validated_data)
        return instance

    def update(self, instance, validated_data):
        for attr in self.Meta.fields:
            setattr(instance, attr, validated_data.get(attr, getattr(instance, attr)))
        if hasattr(validated_data, 'group') and hasattr(validated_data, 'direction'):
            setattr(instance, 'dg_id',
                    Direction.get_pk(getattr(validated_data, 'group'), getattr(validated_data, 'direction')))
        instance.save()
        return instance


class WorkListSerializer(serializers.Serializer):
    students_list_pk = serializers.IntegerField()
    work_manage_pk = serializers.IntegerField()  # 实际上是存作业的id，即WorkManage表的主键
    file_name = serializers.CharField(max_length=300)  # 作业链接
    remark = serializers.CharField(max_length=MAX_MARKDOWN_SIZE, allow_null=True, allow_blank=True)  # 学子的留言，markdown，3M
    time = serializers.DateTimeField()
    normative = serializers.BooleanField()  # 是否规范命名，前端判断吧，，，
    out_time = serializers.BooleanField()  # 是否超时，后端判断
    group = serializers.CharField()
    direction = serializers.CharField()
    # 被谁检查了，还有检查者的留言
    checker = serializers.CharField(allow_null=True, max_length=300)  # 直接后端转义算了

    class Meta:
        model = WorkList
        fields = (
            'students_list_pk', 'work_manage_pk', 'file_name', 'remark', 'time', 'group', 'direction', 'normative', 'out_time', 'checker'
        )

    def to_internal_value(self, data):  # 前端的json传到后端转化为数据库格式
        if data.get('group', None) and data.get('direction'):
            data['dg_id'] = Direction.get_pk(data['group'], data['direction'])
        return super(WorkListSerializer, self).to_internal_value(data)

    def to_representation(self, instance):  # 修改默认映射
        instance.group = Direction.get_group(instance.dg_id)
        instance.direction = Direction.get_direction(instance.dg_id)
        return super(WorkListSerializer, self).to_representation(instance)

    def create(self, validated_data):
        if validated_data.get('group', None) and validated_data.get('direction'):
            validated_data['dg_id'] = Direction.get_pk(validated_data.get('group', None), validated_data.get('direction'))
            validated_data.pop('group')
            validated_data.pop('direction')
        instance = self.Meta.model.objects.create(**validated_data)
        return instance

    def update(self, instance, validated_data):
        for attr in self.Meta.fields:  # todo 之后将这些可以复用的代码抽出来
            if attr == 'group' or attr == 'direction':
                continue
            setattr(instance, attr, validated_data.get(attr, getattr(instance, attr)))
        if hasattr(validated_data, 'group') and hasattr(validated_data, 'direction'):
            setattr(instance, 'dg_id',
                    Direction.get_pk(getattr(validated_data, 'group'), getattr(validated_data, 'direction')))
        instance.save()
        return instance


class WorkManageSerializer(serializers.Serializer):
    name = serializers.CharField(max_length=28, min_length=2)
    message = serializers.CharField(max_length=MAX_MARKDOWN_SIZE)  # 储存markdown文本，上限3M
    DDL = serializers.DateTimeField()
    direction = serializers.CharField()

    class Meta:
        model = WorkManage
        fields = ('name', 'message', 'DDL', 'direction')

    def to_internal_value(self, data):  # 前端的json传到后端转化为数据库格式
        data['direction'] = Direction.get_direction_id(data['direction'])
        return data

    def to_representation(self, instance):  # 修改默认映射
        instance.direction = Direction.direction[instance.direction][1]
        return super(WorkManageSerializer, self).to_representation(instance)

    def create(self, validated_data):
        instance = self.Meta.model.objects.create(**validated_data)
        return instance

    def update(self, instance, validated_data):
        for attr in self.Meta.fields:
            setattr(instance, attr, validated_data.get(attr, getattr(instance, attr)))
        instance.save()
        return instance


class MailSerializer(serializers.Serializer):
    msg = serializers.CharField()
    to = serializers.CharField(required=True, write_only=True)
    sender = serializers.CharField(write_only=True)
    header = serializers.CharField(write_only=True)
    files = serializers.CharField(write_only=True)
    images = serializers.CharField(write_only=True)


class LoginAndRegisterSerializer(serializers.Serializer):
    name = serializers.CharField(max_length=7)
    stu_id = serializers.CharField(max_length=10, min_length=10)
    password = serializers.CharField(max_length=16, min_length=8, write_only=True, )
    qq_id = serializers.CharField(max_length=QQ_ID_MAX_LENGTH)  # 目前最长10位，未来可能会更长
    group = serializers.CharField()
    direction = serializers.CharField()
    is_active = serializers.BooleanField(default=False, read_only=True)  # 学长学姐是否通过了他的注册
    email = serializers.EmailField(allow_blank=True, allow_null=True)
    phone = serializers.CharField(allow_blank=True, allow_null=True, max_length=11, min_length=11)

    class Meta:
        fields = ['name', 'stu_id', 'qq_id', 'group', 'direction', 'email', 'phone', 'password']
